/**
 * @file 高级视图定位(此示例演示如何调整地图视图,以便将几何图形或坐标定位在特定像素位置)
 */
import "assets/styles/common/index.less";
import 'ol/ol.css';
import GeoJSON from 'ol/format/GeoJSON';
import Map from 'ol/Map';
import View from 'ol/View';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';

// 创建矢量数据源
const source = new VectorSource({
  url: '/data/geojson/switzerland.geojson',
  format: new GeoJSON(),
});
// 创建一个style对象(矢量特征渲染样式的容器)
const style = new Style({
  // 填充色
  fill: new Fill({
    color: 'rgba(255, 255, 255, 0.6)',
  }),
  // 边框
  stroke: new Stroke({
    color: '#319FD3',
    width: 1,
  }),
  image: new CircleStyle({
    radius: 5,
    fill: new Fill({
      color: 'rgba(255, 255, 255, 0.6)',
    }),
    stroke: new Stroke({
      color: '#319FD3',
      width: 1,
    }),
  }),
});
// 创建一个矢量图层
const vectorLayer = new VectorLayer({
  source: source,
  style: style,
});
// 创建一个视图
const view = new View({
  center: [0, 0],
  zoom: 1,
});
// 实例化map
const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
    vectorLayer,
  ],
  target: 'map',
  view: view,
});

const zoomtoswitzerland = document.getElementById('zoomtoswitzerland');
zoomtoswitzerland.addEventListener(
  'click',
  function () {
    // 获取特征
    const feature = source.getFeatures()[0];
    // 获取特征下的几何图形
    const polygon = feature.getGeometry();
    // 让视图大小刚好包裹住矢量图形, padding: 内边距[上, 右, 下, 左] 默认值: [0, 0, 0, 0] 单位是像素
    view.fit(polygon, {padding: [170, 50, 30, 150]});
  },
  false
);

const zoomtolausanne = document.getElementById('zoomtolausanne');
zoomtolausanne.addEventListener(
  'click',
  function () {
    const feature = source.getFeatures()[1];
    const point = feature.getGeometry();
    console.log(feature, point, 'yyyyyyyyy')
    // 让视图大小刚好包裹住矢量图形, minResolution: fit函数缩小的最小分辨率 默认值: 0
    view.fit(point, {padding: [170, 50, 30, 150], minResolution: 50});
  },
  false
);

const centerlausanne = document.getElementById('centerlausanne');
centerlausanne.addEventListener(
  'click',
  function () {
    const feature = source.getFeatures()[1];
    const point = feature.getGeometry();
    const size = map.getSize();
    console.log(feature, point, size, 'zzzzzzzzzz')
    // 让视图定位到以point的经纬度为中心点, size单位为像素, 第三个参数是地图dom的中心点
    view.centerOn(point.getCoordinates(), size, [570, 500]);
  },
  false
);
